package com.ids.idtma.map;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.ids.idtma.ActivityBase;
import com.ids.idtma.IdtApplication;
import com.ids.idtma.IdtGroup;
import com.ids.idtma.IdtSetting;
import com.ids.idtma.R;
import com.ids.idtma.jni.aidl.GroupMember;
import com.ids.idtma.util.CurrentGroupCall;
import com.ids.idtma.util.CustomDialog;
import com.ids.idtma.util.SharedPreferencesUtil;

public class IdtMapOffline extends ActivityBase implements
		MKOfflineMapListener, OnItemClickListener {

	private MKOfflineMap mOffline = null;
	private TextView cidView;
	private TextView stateView;
	private TextView page_title_name;
	private AutoCompleteTextView cityNameView;
	private Button start;
	private ArrayList<MKOLSearchRecord> records1;
	private ArrayList<MKOLSearchRecord> records2;
	// private TextView my_num_textview;
	/**
	 * 已下载的离线地图信息列表
	 */
	private ArrayList<MKOLUpdateElement> localMapList = null;
	private LocalMapAdapter lAdapter = null;
	private ArrayList<String> allCities;
	private AllCityListView allCityListView;
	private ScrollView sv;
	private JSONObject mJsonObj;
	private ArrayList<String> cityList = new ArrayList<String>();

	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_offline);
		// 得到一个JSONObject的对象
		initJsonData();
		sv = (ScrollView) findViewById(R.id.id_scroll_sv);
		sv.smoothScrollTo(0, 0);
		IdtApplication.getInstance().addActivity(IdtMapOffline.this);
		mOffline = new MKOfflineMap();
		mOffline.init(this);
		initDatas();
		initView();
	}

	private void initJsonData() {
		try {
			StringBuffer sb = new StringBuffer();
			InputStream is = getAssets().open("city.json");
			int len = -1;
			byte[] buf = new byte[1024];
			while ((len = is.read(buf)) != -1) {
				sb.append(new String(buf, 0, len, "GBK"));
			}
			is.close();
			mJsonObj = new JSONObject(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private String[] mProvinceDatas;
	/**
	 * key - 省 value - 市s
	 */
	private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key - 市 values - 区s
	 */
	private Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();

	private void initDatas() {
		try {
			JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
			mProvinceDatas = new String[jsonArray.length()];
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象
				String province = jsonP.getString("p");// 省名字
				cityList.add(province);
				mProvinceDatas[i] = province;

				JSONArray jsonCs = null;
				try {
					/**
					 * Throws JSONException if the mapping doesn't exist or is
					 * not a JSONArray.
					 */
					jsonCs = jsonP.getJSONArray("c");
				} catch (Exception e1) {
					continue;
				}
				String[] mCitiesDatas = new String[jsonCs.length()];
				for (int j = 0; j < jsonCs.length(); j++) {
					JSONObject jsonCity = jsonCs.getJSONObject(j);
					String city = jsonCity.getString("n");// 市名字
					cityList.add(city);
					mCitiesDatas[j] = city;
					JSONArray jsonAreas = null;
					try {
						/**
						 * Throws JSONException if the mapping doesn't exist or
						 * is not a JSONArray.
						 */
						jsonAreas = jsonCity.getJSONArray("a");
					} catch (Exception e) {
						continue;
					}

					String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区
					for (int k = 0; k < jsonAreas.length(); k++) {
						String area = jsonAreas.getJSONObject(k).getString("s");// 区域的名称
						mAreasDatas[k] = area;
					}
					mAreaDatasMap.put(city, mAreasDatas);
				}

				mCitisDatasMap.put(province, mCitiesDatas);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		mJsonObj = null;
	}

	private void initView() {
		cidView = (TextView) findViewById(R.id.cityid);
		cityNameView = (AutoCompleteTextView) findViewById(R.id.city);
		 autoStrs = (String[]) cityList.toArray(new String[cityList
				.size()]);

		ArrayAdapter<String> searchdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, autoStrs);
		cityNameView.setAdapter(searchdapter);
		stateView = (TextView) findViewById(R.id.state);
		page_title_name = (TextView) findViewById(R.id.page_title_name);
		start = (Button) findViewById(R.id.start);
		page_title_name.setText("离线地图");
		HotCityListView hotCityList = (HotCityListView) findViewById(R.id.hotcitylist);
		ArrayList<String> hotCities = new ArrayList<String>();
		// 获取热闹城市列表
		records1 = mOffline.getHotCityList();
		if (records1 != null) {
			for (MKOLSearchRecord r : records1) {
				// "(" + r.cityID + ")" +
				hotCities.add(r.cityName + "   --"
						+ this.formatDataSize(r.size));
			}
		}
		ListAdapter hAdapter = (ListAdapter) new ArrayAdapter<String>(this,
				R.layout.hotcity_list_item, hotCities);
		hotCityList.setAdapter(hAdapter);
		hotCityList.setOnItemClickListener(this);

		allCityListView = (AllCityListView) findViewById(R.id.allcitylist);
		allCities = new ArrayList<String>();

		records2 = mOffline.getOfflineCityList();
		if (records2 != null) {
			for (MKOLSearchRecord r : records2) {
				/*
				 * allCities.add(r.cityName + "   --" +
				 * this.formatDataSize(r.size));
				 */
				// 如果是省
				if (r.cityType == 1) {
					// 得到省份下面孩子城市的列表
					childcities = r.childCities;
					for (MKOLSearchRecord city : childcities) {
						allCities.add(city.cityName + "   --"
								+ this.formatDataSize(city.size));
					}
				}
			}
		}

		adapter = new NationalCityAdapter(this, records2);
		allCityListView.setAdapter(adapter);
		// allCityListView.setGroupIndicator(IdtMapOffline.this.getResources().getDrawable(R.layout.expandablelistviewselector));
		allCityListView.setGroupIndicator(null);
		allCityListView.setOnGroupExpandListener(new OnGroupExpandListener() {
			// 这个是展开省份的城市列表
			@Override
			public void onGroupExpand(int groupPosition) {
				// 若是下面没有子列表,则直接下载
				if (records2.get(groupPosition).childCities == null) {
					cidView.setText(records2.get(groupPosition).cityID + "");
					cidView.setVisibility(View.GONE);
					cityNameView.setText(records2.get(groupPosition).cityName);
				}
				for (int i = 0; i < adapter.getGroupCount(); i++) {
					if (groupPosition != i) {
						allCityListView.collapseGroup(i);
					}
				}
				adapter.notifyDataSetChanged();
			}
		});
		// 这个是城市的收起操作
		allCityListView
				.setOnGroupCollapseListener(new OnGroupCollapseListener() {
					@Override
					public void onGroupCollapse(final int groupPosition) {
						adapter.getGroup(groupPosition);
						adapter.notifyDataSetChanged();
					}
				});
		// 省份下面的城市点击列表
		allCityListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// 点击选择的城市,将进行城市离线地图下载
				cidView.setText(records2.get(groupPosition).childCities
						.get(childPosition).cityID + "");
				cidView.setVisibility(View.GONE);
				cityNameView.setText(records2.get(groupPosition).childCities
						.get(childPosition).cityName);
				return false;
			}
		});

		allCityListView.setOnItemClickListener(this);
		LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
		LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
		lm.setVisibility(View.GONE);
		cl.setVisibility(View.VISIBLE);

		// 获取已下过的离线地图信息
		localMapList = mOffline.getAllUpdateInfo();
		if (localMapList == null) {
			localMapList = new ArrayList<MKOLUpdateElement>();
		}

		OffCityListView localMapListView = (OffCityListView) findViewById(R.id.localmaplist);
		lAdapter = new LocalMapAdapter();
		localMapListView.setAdapter(lAdapter);
		// my_num_textview = (TextView) findViewById(R.id.my_num);
		// my_num_textview.setText(SharedPreferencesUtil.getStringPreference(getApplicationContext(),
		// "phone_number", ""));
	}

	public void onClick(View view) {
		Intent intent = new Intent();
		switch (view.getId()) {
		case R.id.map:
			// 点击地图图标
			intent.setClass(IdtMapOffline.this, IdtMap.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		case R.id.return_button:
			// 点击屏幕上方返回键
			IdtApplication.getInstance().deleteActivity(this);
			break;
		default:
			break;
		}
	}

	/**
	 * 切换至城市列表
	 * 
	 * @param view
	 */
	public void clickCityListButton(View view) {
		LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
		LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
		lm.setVisibility(View.GONE);
		cl.setVisibility(View.VISIBLE);

	}

	/**
	 * 切换至下载管理列表
	 * 
	 * @param view
	 */
	public void clickLocalMapListButton(View view) {
		LinearLayout cl = (LinearLayout) findViewById(R.id.citylist_layout);
		LinearLayout lm = (LinearLayout) findViewById(R.id.localmap_layout);
		lm.setVisibility(View.VISIBLE);
		cl.setVisibility(View.GONE);
	}

	/**
	 * 搜索离线城市
	 *
	 * @param view
	 */
	public void search(View view) {
		ArrayList<MKOLSearchRecord> records = mOffline.searchCity(cityNameView
				.getText().toString());
		if (records == null || records.size() != 1) {
			Toast.makeText(IdtMapOffline.this,
					"您的输入不规范,请输入正确城市名称,暂不支持市级一下城市下载", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		Toast.makeText(IdtMapOffline.this,
				"搜索到的城市为:" + records.get(0).cityName + ",点击开始按钮进行下载",
				Toast.LENGTH_LONG).show();
		cidView.setText(String.valueOf(records.get(0).cityID));
		cidView.setVisibility(View.GONE);
	}

	/**
	 * 开始下载
	 * 
	 * @param view
	 */
	public void start(View view) {
		String cityName = cityNameView.getText().toString();
		int cityid = 0;
		if (cidView.getText().toString().length() <= 0 || cityName == null
				|| cityName == "") {
			// cityid = Integer.parseInt(cidView.getText().toString().trim());
			Toast.makeText(this, "请输入要下载的城市名称 ", Toast.LENGTH_SHORT).show();
			return;
		} else {
			cityid = Integer.parseInt(cidView.getText().toString());
			mOffline.start(cityid);
			clickLocalMapListButton(null);
			Toast.makeText(this, "开始下载离线地图. 城市: " + cityName,
					Toast.LENGTH_SHORT).show();
			updateView();
		}
	}

	/**
	 * 暂停下载
	 * 
	 * @param view
	 */
	public void stop(View view) {
		String cityName = cityNameView.getText().toString();
		int cityid = 0;
		if (cidView.getText().toString().length() <= 0 || cityName == null
				|| cityName == "") {
			// cityid = Integer.parseInt(cidView.getText().toString().trim());
			Toast.makeText(this, "现在并未开始下载城市 ", Toast.LENGTH_SHORT).show();
			return;
		}
		cityid = Integer.parseInt(cidView.getText().toString().trim());
		mOffline.pause(cityid);
		Toast.makeText(this, "暂停下载离线地图. cityid: " + cityName,
				Toast.LENGTH_SHORT).show();
	}

	/**
	 * 删除离线地图
	 * 
	 * @param view
	 */
	int cityid = 0;
	private NationalCityAdapter adapter;
	private ArrayList<MKOLSearchRecord> childcities;
	private ImageView imageView;
	private String[] autoStrs;

	public void remove(View view) {
		final String cityName = cityNameView.getText().toString();

		if (cidView.getText().toString().length() <= 0 || cityName == null
				|| cityName == "") {
			// cityid = Integer.parseInt(cidView.getText().toString().trim());
			Toast.makeText(this, "请选择要删除的城市 ", Toast.LENGTH_SHORT).show();
			return;
		}
		cityid = Integer.parseInt(cidView.getText().toString().trim());
		new CustomDialog.Builder(this)
				.setTitle("温馨提示")
				.setMessage("您确定删除" + cityName + "吗?")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case AlertDialog.BUTTON_POSITIVE:
							mOffline.remove(cityid);
							Toast.makeText(IdtMapOffline.this,
									"删除离线地图. city: " + cityName,
									Toast.LENGTH_SHORT).show();
							stateView.setText(cityName + ":  0%");
							updateView();
							if (dialog != null) {
								dialog.dismiss();
							}
							break;
						case AlertDialog.BUTTON_NEGATIVE:
							Toast.makeText(IdtMapOffline.this,
									"取消删除离线地图. city: " + cityName,
									Toast.LENGTH_SHORT).show();
							if (dialog != null) {
								dialog.dismiss();
							}
							break;
						default:
							break;
						}

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(IdtMapOffline.this,
								"取消删除离线地图. city: " + cityName,
								Toast.LENGTH_SHORT).show();
						switch (which) {
						case AlertDialog.BUTTON_POSITIVE:
							if (dialog != null) {
								dialog.dismiss();
							}
							break;
						case AlertDialog.BUTTON_NEGATIVE:
							if (dialog != null) {
								dialog.dismiss();
							}
							break;
						default:
							break;
						}
					}
				}).create().show();
		/*
		 * mOffline.remove(cityid); Toast.makeText(this, "删除离线地图. cityid: " +
		 * cityName, Toast.LENGTH_SHORT) .show(); stateView.setText(cityName +
		 * ":  0%"); updateView();
		 */
	}

	/**
	 * 更新状态显示
	 */
	public void updateView() {
		localMapList = mOffline.getAllUpdateInfo();
		if (localMapList == null) {
			localMapList = new ArrayList<MKOLUpdateElement>();
		}
		lAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onPause() {
		int cityid = 0;
		if (cidView.getText().toString().length() <= 0) {
			// cityid = Integer.parseInt(cidView.getText().toString().trim());
			super.onPause();
			return;
		}
		cityid = Integer.parseInt(cidView.getText().toString().trim());
		// int cityid = Integer.parseInt(cidView.getText().toString());
		MKOLUpdateElement temp = mOffline.getUpdateInfo(cityid);
		if (temp != null && temp.status == MKOLUpdateElement.DOWNLOADING) {
			mOffline.pause(cityid);
		}
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	public String formatDataSize(int size) {
		String ret = "";
		if (size < (1024 * 1024)) {
			ret = String.format("%dK", size / 1024);
		} else {
			ret = String.format("%.1fM", size / (1024 * 1024.0));
		}
		return ret;
	}

	@Override
	protected void onDestroy() {
		/**
		 * 退出时，销毁离线地图模块
		 */
		mOffline.destroy();
		super.onDestroy();
		if(autoStrs!=null){
		autoStrs=null;}
	}

	@Override
	public void onGetOfflineMapState(int type, int state) {
		switch (type) {
		case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
			MKOLUpdateElement update = mOffline.getUpdateInfo(state);
			// 处理下载进度更新提示
			if (update != null) {
				stateView.setText(String.format("%s : %d%%", update.cityName,
						update.ratio));
				updateView();
			}
		}
			break;
		case MKOfflineMap.TYPE_NEW_OFFLINE:
			// 有新离线地图安装
			Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));
			break;
		case MKOfflineMap.TYPE_VER_UPDATE:
			// 版本更新提示
			// MKOLUpdateElement e = mOffline.getUpdateInfo(state);

			break;
		default:
			break;
		}
		

	}

	/**
	 * 离线地图管理列表适配器
	 */
	public class LocalMapAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return localMapList.size();
		}

		@Override
		public Object getItem(int index) {
			return localMapList.get(index);
		}

		@Override
		public long getItemId(int index) {
			return index;
		}

		@Override
		public View getView(int index, View view, ViewGroup arg2) {
			MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);
			view = View.inflate(IdtMapOffline.this,
					R.layout.offline_localmap_list, null);
			initViewItem(view, e);
			return view;
		}

		void initViewItem(View view, final MKOLUpdateElement e) {
			Button display = (Button) view.findViewById(R.id.display);
			Button remove = (Button) view.findViewById(R.id.remove);
			TextView title = (TextView) view.findViewById(R.id.title);
			TextView update = (TextView) view.findViewById(R.id.update);
			TextView ratio = (TextView) view.findViewById(R.id.ratio);
			ratio.setText(e.ratio + "%");
			title.setText(e.cityName);
			if (e.update) {
				update.setText("可更新");
			} else {
				update.setText("最新");
			}
			if (e.ratio != 100) {
				display.setEnabled(false);
			} else {
				display.setEnabled(true);
			}
			remove.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					new CustomDialog.Builder(IdtMapOffline.this)
							.setTitle("温馨提示")
							.setMessage("您确定删除" + e.cityName + "吗?")
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											switch (which) {
											case AlertDialog.BUTTON_POSITIVE:
												mOffline.remove(e.cityID);
												Toast.makeText(
														IdtMapOffline.this,
														"删除离线地图. city: "
																+ e.cityName,
														Toast.LENGTH_SHORT)
														.show();
												if(stateView.getText().toString().trim().length()!=0){
													stateView.setText(e.cityName
															+ ":  0%");
												}
												updateView();
												if (dialog != null) {
													dialog.dismiss();
												}
												break;
											case AlertDialog.BUTTON_NEGATIVE:
												Toast.makeText(
														IdtMapOffline.this,
														"取消删除离线地图. city: "
																+ e.cityName,
														Toast.LENGTH_SHORT)
														.show();
												if (dialog != null) {
													dialog.dismiss();
												}
												break;
											default:
												break;
											}
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											switch (which) {
											case AlertDialog.BUTTON_POSITIVE:
												if (dialog != null) {
													dialog.dismiss();
												}
												break;
											case AlertDialog.BUTTON_NEGATIVE:
												if (dialog != null) {
													dialog.dismiss();
												}
												break;
											default:
												break;
											}
										}
									}).create().show();
					//mOffline.remove(e.cityID);
					updateView();
				}
			});
			display.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.putExtra("longitude", e.geoPt.longitude);
					intent.putExtra("latitude", e.geoPt.latitude);
					intent.setClass(IdtMapOffline.this, IdtMap.class);
					startActivity(intent);
				}
			});
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		switch (parent.getId()) {
		case R.id.hotcitylist:
			cidView.setText(records1.get(position).cityID + "");
			cidView.setVisibility(View.GONE);
			cityNameView.setText(records1.get(position).cityName);
			break;

		case R.id.allcitylist:
			cidView.setText(records2.get(position).cityID + "");
			cityNameView.setText(records2.get(position).cityName);
			break;

		default:
			break;
		}
	}

}